import React, { useState, useEffect, useRef } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import axios from 'axios';
import { FaPlus, FaFileAlt, FaTrashAlt, FaEdit, FaShareAlt, FaRobot, FaFileUpload, FaFileImport, FaStop } from 'react-icons/fa';
import NavBar from '../components/NavBar';
import Modal from '../components/Modal';
import ShareModal from '../components/ShareModal';
import './styles.css';
import './Documents.css';
import { toast } from 'react-toastify';

function Documents() {
  const [documents, setDocuments] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [showShareModal, setShowShareModal] = useState(false);
  const [showAiModal, setShowAiModal] = useState(false);
  const [showImportModal, setShowImportModal] = useState(false);
  const [newDocTitle, setNewDocTitle] = useState('');
  const [selectedDoc, setSelectedDoc] = useState(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [importTitle, setImportTitle] = useState('');
  const [selectedMarkdownFile, setSelectedMarkdownFile] = useState(null);
  const importFileInputRef = useRef(null);
  const navigate = useNavigate();
  
  // AI处理相关状态
  const [aiPrompt, setAiPrompt] = useState('');
  const [selectedFile, setSelectedFile] = useState(null);
  const [isProcessing, setIsProcessing] = useState(false);
  const [isImporting, setIsImporting] = useState(false);
  const [processStatus, setProcessStatus] = useState(null);
  const [processProgress, setProcessProgress] = useState(0);
  const [processMessage, setProcessMessage] = useState('');
  const [processId, setProcessId] = useState(null);
  const [processError, setProcessError] = useState(null);
  const [processPollInterval, setProcessPollInterval] = useState(null);
  const [aiGeneratedContent, setAiGeneratedContent] = useState('');
  const [terminating, setTerminating] = useState(false);

  // 加载文档列表
  useEffect(() => {
    fetchDocuments();
  }, []);

  const fetchDocuments = async () => {
    setLoading(true);
    try {
      const response = await axios.get('/api/docs');
      setDocuments(response.data.sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at)));
    } catch (error) {
      console.error('获取文档失败:', error);
      toast.error('获取文档列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleCreateDoc = async () => {
    if (!newDocTitle.trim()) {
      toast.warning('请输入文档标题');
      return;
    }

    try {
      const response = await axios.post('/api/docs', { title: newDocTitle });
      setShowCreateModal(false);
      setNewDocTitle('');
      navigate(`/editor/${response.data.id}`);
    } catch (error) {
      console.error('创建文档失败:', error);
      toast.error('创建文档失败');
    }
  };

  const handleDeleteDoc = async () => {
    if (!selectedDoc) return;

    try {
      await axios.delete(`/api/docs/${selectedDoc.id}`);
      setDocuments(documents.filter(doc => doc.id !== selectedDoc.id));
      setShowDeleteModal(false);
      toast.success('文档已删除');
    } catch (error) {
      console.error('删除文档失败:', error);
      toast.error('删除文档失败');
    }
  };

  const confirmDelete = (doc) => {
    setSelectedDoc(doc);
    setShowDeleteModal(true);
  };

  const handleShare = (doc) => {
    setSelectedDoc(doc);
    setShowShareModal(true);
  };
  
  // 打开AI处理模态框
  const openAiModal = () => {
    setShowAiModal(true);
    setAiPrompt('');
    setSelectedFile(null);
  };
  
  // 打开导入Markdown模态框
  const openImportModal = () => {
    setShowImportModal(true);
    setImportTitle('');
    setSelectedMarkdownFile(null);
  };
  
  // 处理文件选择
  const handleFileChange = (e) => {
    const file = e.target.files[0];
    if (file) {
      // 检查文件类型
      const fileExt = file.name.split('.').pop().toLowerCase();
      if (fileExt !== 'docx' && fileExt !== 'pdf') {
        toast.error('只支持Word(.docx)和PDF(.pdf)文件');
        return;
      }
      
      // 检查文件大小
      if (file.size > 20 * 1024 * 1024) { // 20MB
        toast.error('文件大小不能超过20MB');
        return;
      }
      
      setSelectedFile(file);
    }
  };
  
  // 处理Markdown文件选择
  const handleMarkdownFileChange = (e) => {
    const file = e.target.files[0];
    if (file) {
      // 检查文件类型
      const fileExt = file.name.split('.').pop().toLowerCase();
      if (fileExt !== 'md' && fileExt !== 'markdown') {
        toast.error('只支持Markdown(.md/.markdown)文件');
        return;
      }
      
      // 检查文件大小
      if (file.size > 10 * 1024 * 1024) { // 10MB
        toast.error('文件大小不能超过10MB');
        return;
      }
      
      // 从文件名中提取标题（默认值）
      const fileName = file.name.replace(/\.[^/.]+$/, "");
      setImportTitle(fileName);
      setSelectedMarkdownFile(file);
    }
  };
  
  // 提交AI处理请求
  const handleAiProcess = async () => {
    if (!selectedFile) {
      toast.warning('请选择一个文件');
      return;
    }
    
    if (!aiPrompt.trim()) {
      toast.warning('请输入处理指令');
      return;
    }
    
    setIsProcessing(true);
    setProcessStatus('pending');
    setProcessProgress(0);
    setProcessMessage('正在准备处理...');
    setProcessError(null);
    
    try {
      const formData = new FormData();
      formData.append('document', selectedFile);
      formData.append('prompt', aiPrompt);
      
      // 获取文件名作为标题，去掉扩展名，不再强制添加"AI处理:"前缀
      const fileTitle = selectedFile.name.replace(/\.[^/.]+$/, "");
      formData.append('title', fileTitle);
      
      const response = await axios.post('/api/ai/process-document', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      
      // 保存处理ID并开始轮询进度
      const newProcessId = response.data.processId;
      setProcessId(newProcessId);
      startPollingProgress(newProcessId);
      
    } catch (error) {
      console.error('AI处理文档失败:', error);
      toast.error(error.response?.data?.message || '处理文档失败');
      setIsProcessing(false);
      setProcessStatus('failed');
      setProcessError(error.response?.data?.message || '处理文档失败');
    }
  };
  
  // 轮询处理进度
  const startPollingProgress = (procId) => {
    // 清除之前的轮询
    if (processPollInterval) {
      clearInterval(processPollInterval);
    }
    
    // 清空之前的生成内容
    setAiGeneratedContent('');
    
    // 创建新的轮询
    const intervalId = setInterval(async () => {
      try {
        const response = await axios.get(`/api/ai/process-status/${procId}`);
        const { status, progress, message, error, result } = response.data;
        
        setProcessStatus(status);
        setProcessProgress(progress);
        
        // 处理进度消息
        if (message) {
          setProcessMessage(message);
          
          // 检查消息中是否包含生成的内容摘要
          if (message.includes('最近内容:')) {
            // 提取最新生成的内容部分
            const contentPart = message.split('最近内容:')[1].trim();
            
            // 直接设置为最新内容，不再追加
            // 这样可以实时显示AI生成的最新部分
            setAiGeneratedContent(contentPart);
          }
        }
        
        if (error) {
          setProcessError(error);
        }
        
        // 处理完成或失败时
        if (status === 'completed' || status === 'failed') {
          clearInterval(intervalId);
          setProcessPollInterval(null);
          
          if (status === 'completed' && result) {
            toast.success('文档处理成功');
            setShowAiModal(false);
            setIsProcessing(false);
            
            // 刷新文档列表并导航到新创建的文档
            fetchDocuments();
            navigate(`/editor/${result.docId}`);
          } else if (status === 'failed') {
            toast.error(error || '处理文档失败');
            setIsProcessing(false);
          }
        }
      } catch (error) {
        console.error('获取处理进度失败:', error);
        // 如果获取进度失败，则停止轮询
        clearInterval(intervalId);
        setProcessPollInterval(null);
        setIsProcessing(false);
        setProcessStatus('failed');
        setProcessError('获取处理进度失败');
      }
    }, 500); // 每500毫秒轮询一次，提高实时性
    
    setProcessPollInterval(intervalId);
  };
  
  // 组件卸载时清除轮询
  useEffect(() => {
    return () => {
      if (processPollInterval) {
        clearInterval(processPollInterval);
      }
    };
  }, [processPollInterval]);
  
  // 导入Markdown文件
  const handleImportMarkdown = async () => {
    if (!selectedMarkdownFile) {
      toast.warning('请选择一个Markdown文件');
      return;
    }
    
    if (!importTitle.trim()) {
      toast.warning('请输入文档标题');
      return;
    }
    
    setIsImporting(true);
    
    try {
      const formData = new FormData();
      formData.append('markdown', selectedMarkdownFile);
      formData.append('title', importTitle);
      
      const response = await axios.post('/api/docs/import-markdown', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      
      toast.success('Markdown文件导入成功');
      setShowImportModal(false);
      
      // 导航到新创建的文档
      navigate(`/editor/${response.data.docId}`);
    } catch (error) {
      console.error('导入Markdown文件失败:', error);
      toast.error(error.response?.data?.message || '导入失败');
    } finally {
      setIsImporting(false);
    }
  };

  const handleTerminateAI = async () => {
    setTerminating(true);
    try {
      await axios.post('/api/ai/terminate-process', { processId });
      setShowAiModal(false);
      setIsProcessing(false);
      setProcessStatus('failed');
      setProcessError('AI生成已终止');
    } catch (error) {
      console.error('终止AI生成失败:', error);
      toast.error('终止AI生成失败');
    } finally {
      setTerminating(false);
    }
  };

  const filteredDocuments = documents.filter(doc => 
    doc.title.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <div className="documents-container">
      <NavBar />
      
      <div className="documents-header">
        <h1>我的文档</h1>
        <div className="documents-actions">
          <button 
            className="btn btn-primary" 
            onClick={() => setShowCreateModal(true)}
          >
            <FaPlus /> 新建文档
          </button>
          <button 
            className="btn btn-success" 
            onClick={openImportModal}
          >
            <FaFileImport /> 导入Markdown
          </button>
          <button 
            className="btn btn-secondary" 
            onClick={openAiModal}
          >
            <FaFileUpload /> 上传并处理文档
          </button>
        </div>
      </div>
      
      <div className="search-container">
        <input 
          type="text" 
          placeholder="搜索文档..." 
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          className="search-input"
        />
      </div>
      
      {loading ? (
        <div className="loading">加载中...</div>
      ) : (
        <>
          {filteredDocuments.length === 0 ? (
            <div className="no-documents">
              <p>没有找到文档</p>
              <div className="no-docs-actions">
                <button 
                  className="btn btn-primary" 
                  onClick={() => setShowCreateModal(true)}
                >
                  创建新文档
                </button>
                <button 
                  className="btn btn-success" 
                  onClick={openImportModal}
                >
                  导入Markdown
                </button>
              </div>
            </div>
          ) : (
            <div className="documents-grid">
              {filteredDocuments.map(doc => (
                <div key={doc.id} className="document-card">
                  <div className="document-card-header">
                    <h3>{doc.title}</h3>
                    <div className="document-actions">
                      <button 
                        onClick={() => handleShare(doc)} 
                        className="action-btn"
                        title="分享"
                      >
                        <FaShareAlt />
                      </button>
                      <button 
                        onClick={() => confirmDelete(doc)} 
                        className="action-btn delete-btn"
                        title="删除"
                      >
                        <FaTrashAlt />
                      </button>
                    </div>
                  </div>
                  <div className="document-card-body">
                    <p>
                      {doc.content ? 
                        doc.content.substring(0, 100) + (doc.content.length > 100 ? '...' : '') : 
                        '空文档'}
                    </p>
                  </div>
                  <div className="document-card-footer">
                    <span className="document-date">
                      更新于: {new Date(doc.updated_at).toLocaleString()}
                    </span>
                    <Link to={`/editor/${doc.id}`} className="btn btn-sm btn-primary">
                      <FaEdit /> 编辑
                    </Link>
                  </div>
                </div>
              ))}
            </div>
          )}
        </>
      )}
      
      {/* 创建文档的模态框 */}
      <Modal
        isOpen={showCreateModal}
        onClose={() => setShowCreateModal(false)}
        title="创建新文档"
      >
        <div className="form-group">
          <label htmlFor="docTitle">文档标题</label>
          <input 
            type="text" 
            id="docTitle" 
            value={newDocTitle}
            onChange={(e) => setNewDocTitle(e.target.value)}
            placeholder="输入文档标题..."
            className="form-control"
          />
        </div>
        <div className="modal-actions">
          <button 
            className="btn btn-secondary" 
            onClick={() => setShowCreateModal(false)}
          >
            取消
          </button>
          <button 
            className="btn btn-primary" 
            onClick={handleCreateDoc}
          >
            创建
          </button>
        </div>
      </Modal>
      
      {/* 删除确认模态框 */}
      <Modal
        isOpen={showDeleteModal}
        onClose={() => setShowDeleteModal(false)}
        title="确认删除"
      >
        <div className="delete-confirmation">
          <p>确定要删除 "{selectedDoc?.title}" 吗？</p>
          <p className="warning">删除后无法恢复！</p>
          <div className="modal-actions">
            <button 
              className="btn btn-secondary" 
              onClick={() => setShowDeleteModal(false)}
            >
              取消
            </button>
            <button 
              className="btn btn-danger" 
              onClick={handleDeleteDoc}
            >
              删除
            </button>
          </div>
        </div>
      </Modal>
      
      {/* 分享模态框 */}
      {showShareModal && (
        <ShareModal 
          isOpen={showShareModal}
          onClose={() => setShowShareModal(false)}
          document={selectedDoc}
        />
      )}
      
      {/* AI处理文档模态框 */}
      <Modal
        isOpen={showAiModal}
        onClose={() => {
          if (!isProcessing || processStatus === 'failed') {
            setShowAiModal(false);
          }
        }}
        title="使用AI处理文档"
      >
        <div className="ai-form">
          <div className="form-group">
            <label htmlFor="fileUpload">选择文件</label>
            <input 
              type="file" 
              id="fileUpload" 
              accept=".docx,.pdf"
              onChange={handleFileChange}
              className="form-control"
              disabled={isProcessing}
            />
            {selectedFile && (
              <div className="selected-file">
                已选择: {selectedFile.name}
              </div>
            )}
          </div>
          
          <div className="form-group">
            <label htmlFor="aiPrompt">处理指令</label>
            <textarea 
              id="aiPrompt"
              value={aiPrompt}
              onChange={(e) => setAiPrompt(e.target.value)}
              placeholder="输入AI处理指令，例如：'总结文档内容并提取关键点'"
              className="form-control"
              rows={4}
              disabled={isProcessing}
            />
          </div>
          
          {isProcessing && (
            <div className="process-status">
              <div className="process-info">
                <span>{processMessage.split('\n')[0]}</span>
                <span className="progress-percent">{processProgress}%</span>
              </div>
              <div className="progress-bar-container">
                <div 
                  className="progress-bar" 
                  style={{ width: `${processProgress}%` }}
                ></div>
              </div>
              
              {/* 终止生成按钮 */}
              {isProcessing && processStatus !== 'completed' && processStatus !== 'failed' && (
                <div className="terminate-container">
                  <button 
                    className="terminate-button" 
                    onClick={handleTerminateAI}
                    disabled={terminating}
                  >
                    <FaStop className="terminate-icon" /> {terminating ? '正在终止...' : '终止AI生成'}
                  </button>
                </div>
              )}
              
              {/* 显示生成的内容 */}
              {aiGeneratedContent && (
                <div className="ai-generated-content">
                  <h4>
                    <div>
                      <span className="live-indicator"></span>
                      AI生成内容实时预览
                    </div>
                    <span className="content-length">{processStatus === 'completed' ? '生成完成' : '生成中...'}</span>
                  </h4>
                  <div 
                    className="content-preview auto-scroll"
                    ref={(el) => {
                      // 自动滚动到底部
                      if (el) {
                        el.scrollTop = el.scrollHeight;
                      }
                    }}
                  >
                    {aiGeneratedContent}
                  </div>
                </div>
              )}
              
              {processStatus === 'failed' && processError && (
                <div className="process-error">
                  错误: {processError}
                </div>
              )}
            </div>
          )}
          
          <div className="modal-actions">
            <button 
              className="btn btn-secondary" 
              onClick={() => {
                if (!isProcessing || processStatus === 'failed') {
                  setShowAiModal(false);
                }
              }}
              disabled={isProcessing && processStatus !== 'failed'}
            >
              {isProcessing && processStatus !== 'failed' ? '处理中...' : '取消'}
            </button>
            <button 
              className="btn btn-primary" 
              onClick={handleAiProcess}
              disabled={isProcessing}
            >
              {isProcessing ? '正在处理...' : '开始处理'}
            </button>
          </div>
        </div>
      </Modal>
      
      {/* 导入Markdown文件模态框 */}
      <Modal
        isOpen={showImportModal}
        onClose={() => setShowImportModal(false)}
        title="导入Markdown文件"
      >
        <div className="import-form">
          <div className="form-group">
            <label htmlFor="markdownUpload">选择Markdown文件</label>
            <input 
              type="file" 
              id="markdownUpload" 
              accept=".md,.markdown"
              onChange={handleMarkdownFileChange}
              className="form-control"
              ref={importFileInputRef}
            />
            {selectedMarkdownFile && (
              <div className="selected-file">
                已选择: {selectedMarkdownFile.name}
              </div>
            )}
          </div>
          
          <div className="form-group">
            <label htmlFor="importTitle">文档标题</label>
            <input 
              type="text" 
              id="importTitle" 
              value={importTitle}
              onChange={(e) => setImportTitle(e.target.value)}
              placeholder="输入文档标题..."
              className="form-control"
            />
          </div>
          
          <div className="modal-actions">
            <button 
              className="btn btn-secondary" 
              onClick={() => setShowImportModal(false)}
              disabled={isImporting}
            >
              取消
            </button>
            <button 
              className="btn btn-success" 
              onClick={handleImportMarkdown}
              disabled={isImporting}
            >
              {isImporting ? '导入中...' : '导入文件'}
            </button>
          </div>
        </div>
      </Modal>
    </div>
  );
}

export default Documents; 